const Router = require('koa-router');
const userRouter = new Router();
// 数据库
const { User } = require('../db/index');

// 前缀
userRouter.prefix('/user');

userRouter.
    get('/test',async (ctx)=>{
        console.log(ctx)
        ctx.body = {
            msg:'success'
        }
    }).
    post('/register',async (ctx)=>{

        let { account, password  } = ctx.request.body;
        // 实例化model 得到 doc文档
        let user = new User({
            account , password
        });

        // 先判断这个账号是否被占用
        let zhanyong = await User.find({ account: account});
        if(zhanyong.length !== 0){
            ctx.body = {
                msg:'这个账号已被占用'
            }
            return;
        }
        
        // 文档.save()  插入数据
        let res = await user.save();

        if(res){
            ctx.body = {
                result : res,
                msg:'success'
            }
        }

    })

module.exports = userRouter;